import ntptime
import sys
import ujson
import urequests
from config import Config
from time import sleep
import network


def connect_to_internet():
	station = network.WLAN(network.STA_IF)

	station.active(False)
	station.active(True)

	print("\nConnecting to network...")

	station.connect(Config.WIFI_SSID, Config.WIFI_PASSWORD)

	while not station.isconnected():
		result_code = station.status()

		if (result_code == network.STAT_IDLE or
			result_code == network.STAT_CONNECT_FAIL or
			result_code == network.STAT_GOT_IP or
			result_code == network.STAT_NO_AP_FOUND or
			result_code == network.STAT_WRONG_PASSWORD):
			break
		elif result_code == network.STAT_CONNECTING:
			pass

		sleep(0.5)

	result_code = station.status()

	print("Connected")

	return result_code


def sync_time():
	ntptime.host = Config.NTP_HOST
	ntptime.NTP_DELTA = 2209017600 - 8 * 60 * 60  # 1900-01-01 00:00:00 - 8h

	try:
		ntptime.time()
		ntptime.settime()
	except OSError:
		return False

	return True


def reset():
	"""
	a soft reset
	"""

	sys.exit()


def update_temperature(temp1, temp2):
	"""
	update data to web server
	"""

	data = Config.POST_DATA % (temp1, temp2)

	try:
		response = urequests.post(Config.UPDATE_TEMPERATURE_URI, data=data, headers=Config.HEADERS)

		if response.text:
			result = ujson.loads(response.text)

			if result[Config.RESULT] == Config.ERROR_CODE:
				print(str(result[Config.ERROR_MSG], "utf-8"))
	# except OSError as ose:
	#	if str(ose) == "[Errno 103] ECONNABORTED":
	#		print("cannot update data")
	except Exception as e:
		log(e)


def log(msg):
	print(str(msg))

	filename = r"log.txt"

	with open(filename, "a+") as file:
		# now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
		file.write("[%s]: %s\n" % (__name__, str(msg)))
		file.flush()


def read_log():
	filename = r"log.txt"

	with open(filename, "r+") as file:
		print(file.read())
